/*
 * main.c
 *
 *  Created on: 2011-7-5
 *      Author: rendong01
 */

#include <stdio.h>
#include <signal.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "core/sgc_config.h"
#include "logic/sgc_connections.h"

void parse_arguments(int argc, char ** argv);
void sgc_daemon();

/**
 * main
 */
int main (int argc, char ** argv)
{
	parse_arguments (argc, argv);

	if (cfg_is_daemon)
		sgc_daemon();

	struct sigaction sa;
	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, 0);

	sgc_start_chat_server();

	return 0;
}

/**
 * 启动后台程序
 */
void sgc_daemon()
{
	int fd;

	switch (fork()){
	case -1:
		sgc_log_error("fork error\n");
		exit(1);
		break;
	case 0: // child
		break;
	default:// parent
		exit(0);
	}

	if (setsid() == -1){
		sgc_log_error("setsid() failed\n");
		exit(1);
	}

	umask(0);

	fd = open("/dev/null", O_RDWR);
	if (fd == -1) {
		sgc_log_error("open /dev/null fail\n");
		exit(1);
	}

	if (dup2(fd, STDIN_FILENO) == -1) {
		sgc_log_error("dup2 STDIN fail\n");
		exit(1);
	}

	if (dup2(fd, STDOUT_FILENO) == -1) {
		sgc_log_error("dup2 STDOUT fail\n");
		exit(1);
	}

	if (dup2(fd, STDERR_FILENO) == -1) {
		sgc_log_error("dup2 STDERR fail\n");
		exit(1);
	}

	if (fd > STDERR_FILENO) {
		if (close(fd) == -1) {
			sgc_log_error("close() fail\n");
			exit(1);
		}
	}
}

/**
 * 解析命令行参数
 */
void parse_arguments(int argc, char ** argv)
{
	char *l_opt_arg;
	struct option long_options[] = {
	{ "help",	0,	NULL,	'h'},
	{ "ip",		1,	NULL, 	'i'},
	{ "port",	1,	NULL,	'p'},
	{ "daemon",	1,	NULL,	'd'},
	{  0,    0,    0,    0},
	};

	int c;
	while((c = getopt_long (argc, argv, "hi:p:d", long_options, NULL)) != -1)
	{
		switch (c)
		{
			case 'i':
				cfg_local_addr = optarg;
				break;
			case 'p':
				l_opt_arg = optarg;
				cfg_port = atoi(l_opt_arg);
				break;
			case 'd':
				cfg_is_daemon = 1;
				break;
			case 'h':
			case '?':
				printf("Usage: %s [OPTION]...\n\
default ip=0.0.0.0 port=843\n\n\
  -i, --ip=ip host        server bind ip\n\
  -p, --port=socket port  server socket port\n\
  -d, --daemon            daemon\n\
  -h, --help              display this help and exit\n\n", argv[0]);
				exit(1);
				break;
		}
	}
}
